<template>
  <t-modal
    :title="operateType == 1 ? '新增' : '编辑'"
    width="900px"
    :visible="visible"
    @cancel="closeModal()"
    @ok="handelOk()"
    wrapClassName="addVolumeModal-container"
    v-bind="footer"
    forceRender
  >
    <div class="curve-modal-body">
      <a-form-model ref="ruleForm" :model="form" :rules="rules">
        <a-form-model-item label="文件编号">
          <a-input
            v-model.trim="form.fileCode"
            placeholder="请输入"
            class="quote"
            :disabled="checkSoucre.fileCode ? true : false"
          />
          <span class="suffix" @click="handleQuote()">
            检索
          </span>
        </a-form-model-item>
        <a-form-model-item label="责任者" prop="responsibility">
          <a-input v-model.trim="form.responsibility" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="文件材料题名" prop="fileTitle">
          <a-input
            v-model.trim="form.fileTitle"
            placeholder="请输入"
            class="quote"
            :disabled="checkSoucre.fileName ? true : false"
          />
          <span class="suffix" @click="handleQuote()">
            检索
          </span>
        </a-form-model-item>
        <a-form-model-item
          label="文件"
          prop="fileList"
          :rules="{
            required: false,
            message: '请选择文件',
          }"
        >
          <bjUploadFile
            :viewMode="checkSoucre.dfsFileUuid ? true : false"
            type="pdf"
            :count="1"
            v-model="form.fileList"
            @download="downloadFile($event)"
            @change="upLoadFile($event)"
            @preview="viewFile($event)"
            :replaceFields="{
              fileName: 'fileName',
              fileSize: 'fileSize',
              fileType: 'fileType',
            }"
          ></bjUploadFile>
        </a-form-model-item>
        <a-form-model-item label="描述" prop="describeinfo">
          <a-input
            v-model.trim="form.describeinfo"
            placeholder="请输入"
            type="textarea"
            :rows="4"
          />
        </a-form-model-item>
        <a-form-model-item label="时间" prop="uploadTime">
          <a-date-picker
            style="width: 100%"
            v-model="form.uploadTime"
            format="YYYY-MM-DD"
            valueFormat="YYYY-MM-DD"
          />
        </a-form-model-item>
        <a-form-model-item label="页次" prop="pageRange">
          <a-input v-model.trim="form.pageRange" placeholder="请输入" />
        </a-form-model-item>
        <a-form-model-item label="备注" prop="remark">
          <a-input
            v-model.trim="form.remark"
            placeholder="请输入"
            type="textarea"
            :rows="4"
          />
        </a-form-model-item>
      </a-form-model>
    </div>
    <!-- 附件预览弹窗 -->
    <previewModal
      ref="previewModal"
      :visible.sync="previewModal.visible"
      :loading="previewModal.loading"
    ></previewModal>

    <!-- 检索引用 -->
    <retrievalQuoteModal
      :visible.sync="retrievalQuoteModal.visible"
      :fileCode="retrievalQuoteModal.fileCode"
      :fileName="retrievalQuoteModal.fileName"
      @retrievalChange="retrievalChange"
    ></retrievalQuoteModal>
  </t-modal>
</template>

<script>
import { axios } from "@/utils/request";
import { mapGetters } from "vuex";
import { getToken } from "@/utils/TopVUI";
import { downloadDfs } from "@/utils/TopVUI";
//上传
import bjUploadFile from "@/components/extendCustom/bj-upload-file";
//预览
import previewModal from "@/pages/document/minio/previewModal";
//检索引用
import retrievalQuoteModal from "./retrievalQuoteModal.vue";
import { saveVolume, detailVolume, updateVolume } from "@/api/safetyManage";
export default {
  components: {
    bjUploadFile,
    previewModal,
    retrievalQuoteModal,
  },
  props: {
    visible: {
      type: Boolean,
      default: false,
    },
    operateType: {
      type: [String, Number],
      default: "1",
    },
    parameter: {
      type: Object,
      default() {
        return {};
      },
    },
    footer: {
      type: Object,
      default() {
        return {};
      },
    },
  },
  data() {
    return {
      form: {
        //文件编号
        fileCode: "",
        //责任者
        responsibility: "",
        //文件材料题名
        fileTitle: "",
        //文件
        fileList: [],
        //描述
        describeinfo: "",
        //时间
        uploadTime: "",
        //页次
        pageRange: "",
        //备注
        remark: "",
      },
      rules: {
        fileCode: [
          {
            required: true,
            message: "请输入文件编号",
          },
        ],
        responsibility: [
          {
            required: true,
            message: "请输入责任者",
          },
        ],
        fileTitle: [
          {
            required: true,
            message: "请输入文件材料题名",
          },
        ],
        uploadTime: [
          {
            required: true,
            message: "请选择时间",
          },
        ],
      },
      //预览
      previewModal: {
        visible: false,
        loading: false,
      },
      //检索引用
      retrievalQuoteModal: {
        visible: false,
        //编号
        fileCode: "",
        //名称
        fileName: "",
      },
      checkSoucre: {},
    };
  },
  computed: {
    ...mapGetters(["configData"]),
    kkFileView() {
      let index = this.configData.findIndex(
        (item) => item.code === "kkFileView"
      );
      if (index >= 0) {
        return this.configData[index].value;
      } else {
        return "http://192.168.1.216:8012/onlinePreview";
      }
    },
  },
  watch: {
    visible: {
      handler(val) {
        this.$emit("update:visible", val);
        if (val) {
          let { uuid } = this.parameter;
          if (uuid) {
            this.getDetail();
          }
        }
      },
      immediate: true,
    },
  },

  methods: {
    saveVolume,
    updateVolume,
    //预览
    viewFile(file) {
      let { url } = file;
      this.previewModal.loading = true;
      this.$refs.previewModal.type = "file";
      this.$refs.previewModal.fileUrl =
        this.kkFileView +
        "/onlinePreview?url=" +
        encodeURIComponent(Base64.encode(url)) +
        "&watermarkTxt=" +
        //水印内容
        encodeURIComponent("") +
        "&token=" +
        getToken();
      this.previewModal.visible = true;
      this.previewModal.loading = false;
    },
    //下载
    downloadFile(row) {
      let { url } = row;
      if (!url) {
        this.$message.success("文件不存在", 1.5);
        return;
      }
      downloadDfs(url);
    },
    //上传附件
    upLoadFile({ file, index }) {
      let formData = new FormData();
      formData.append("bucket", "yx-cloud-vue");
      formData.append("file", file);
      this.$set(this.form["fileList"][index], "loading", true);
      axios
        .post(`/document/minio/uploadfile`, formData, {
          headers: {
            "Content-Type": "multipart/form-data",
          },
        })
        .then((res) => {
          this.$set(
            this.form.fileList[this.form.fileList.length - 1],
            "dfsFileUuid",
            res.dfsFileUuid
          );
          this.$set(
            this.form.fileList[this.form.fileList.length - 1],
            "url",
            res.url
          );
        })
        .catch((_) => {
          this.$set(this.form["fileList"][index], "fail", true);
        })
        .finally((_) => {
          this.$set(this.form["fileList"][index], "loading", false);
        });
    },

    getDetail() {
      let { uuid } = this.parameter;
      return new Promise((resolve, reject) => {
        detailVolume({ uuid })
          .then((res) => {
            let { data } = res;
            this.form = {
              //文件编号
              fileCode: data.fileCode,
              //责任者
              responsibility: data.responsibility,
              //文件材料题名
              fileTitle: data.fileTitle,
              //文件
              fileList: [],
              //描述
              describeinfo: data.describeinfo,
              //时间
              uploadTime: data.uploadTime,
              //页次
              pageRange: data.pageRange,
              //备注
              remark: data.remark,
            };
            //附件
            if (data?.fileInfo) {
              let lastIdx = data?.fileInfo?.fileName.lastIndexOf(".");
              let fileType =
                "." + data.fileInfo.fileName.substring(lastIdx + 1);
              let { uuid, url, fileName, fileSize } = data.fileInfo;
              this.form.fileList.push({
                dfsFileUuid: uuid,
                fileType,
                url,
                fileName,
                fileSize,
              });
            }

            resolve();
          })
          .catch((_) => {
            reject();
          })
          .finally((_) => {});
      });
    },
    handelOk() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          let { form } = this;
          let { directoryUuid, uuid } = this.parameter;
          let ids = form.fileList.map((v) => v.dfsFileUuid);
          let formJson = {
            //文件编号
            fileCode: form.fileCode,
            //责任者
            responsibility: form.responsibility,
            //文件材料题名
            fileTitle: form.fileTitle,
            //文件
            dfsFileUuid: ids.toString(),
            //描述
            describeinfo: form.describeinfo,
            //时间
            uploadTime: form.uploadTime,
            //页次
            pageRange: form.pageRange,
            //备注
            remark: form.remark,
          };
          let url = "";
          //编辑
          if (uuid) {
            formJson.uuid = uuid;
            url = "updateVolume";
          } else {
            formJson.directoryUuid = directoryUuid;
            url = "saveVolume";
          }
          this[url](formJson)
            .then((res) => {
              if (res.statusCode === 200 || res === 1) {
                this.$message.success("操作成功", 1.5);
                this.closeModal();
                this.$emit("ok");
              } else {
                this.$message.error(res?.message ?? "操作失败");
              }
            })
            .catch((_) => {});
        }
      });
    },
    //重置表单
    resetForm() {
      this.checkSoucre = {};
      this.form = {
        //文件编号
        fileCode: "",
        //责任者
        responsibility: "",
        //文件材料题名
        fileTitle: "",
        //文件
        fileList: [],
        //描述
        describeinfo: "",
        //时间
        uploadTime: "",
        //页次
        pageRange: "",
        //备注
        remark: "",
      };
      this.$refs.ruleForm.resetFields();
    },
    //检索引用
    handleQuote() {
      let { fileCode, fileTitle } = this.form;
      this.retrievalQuoteModal.fileCode = fileCode;
      this.retrievalQuoteModal.fileName = fileTitle;
      this.retrievalQuoteModal.visible = true;
    },
    //选择的文件
    retrievalChange(data) {
      let { fileCode, fileName, dfsFileUuid, url } = data;
      this.checkSoucre = data;
      this.form.fileCode = fileCode;
      this.form.fileTitle = fileName;
      if (fileName) {
        let lastIdx = fileName.lastIndexOf(".");
        let fileType = "." + fileName.substring(lastIdx + 1);
        this.form.fileList = [
          {
            fileName: fileName,
            fileType,
            dfsFileUuid: dfsFileUuid,
            url: url,
          },
        ];
      }
    },
    //关闭
    closeModal() {
      this.resetForm();
      this.$emit("update:visible", false);
    },
  },
};
</script>

<style lang="less" scoped>
/deep/.addVolumeModal-container {
  .curve-modal-body {
    max-height: 700px;
    overflow: auto;
    overflow-x: hidden;
  }
  .ant-form-item {
    display: flex;
    .ant-form-item-label {
      flex-shrink: 0;
      width: 100px;
    }
    .ant-form-item-control-wrapper {
      flex: 1;
      overflow: hidden;
      .quote {
        padding-right: 46px;
      }
      .suffix {
        cursor: pointer;
        position: absolute;
        right: 6px;
        top: -11px;
        font-family: Microsoft YaHei, Microsoft YaHei;
        font-weight: 400;
        font-size: 14px;
        color: #1677ff;
        letter-spacing: 1px;
      }
      .bj-upload-file {
        .choosed-file-warp {
          width: 100%;
        }
      }
    }
  }
}
</style>
